import axios from 'axios'
import {
    MessageBox,
    Message
} from 'element-ui'
import store from '@/store'
import {
    removeAccessToken,
    getAccessToken,
    removeRefreshToken,
    setAccessToken,
    getRefreshToken
} from "@/utils/auth"
import router from "@/router"
// create an axios instance
console.log('baseUrl', process.env)
const service = axios.create({
        baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
        // withCredentials: true, // send cookies when cross-domain requests
        timeout: 5000 // request timeout
    })
    // 标志变量，用于跟踪是否已经执行了刷新accessToken的操作
let isRefreshing = false;
import {
    Refresh
} from "@/api/modules/user"
// 需要重新发送的请求队列
let requestsQueue = [];
// request interceptor  
service.interceptors.request.use(
    config => {

        const accessToken = getAccessToken()
        console.log(accessToken)
            // console.log(config)
            // 如果存在accessToken并且header不存在用户验证
        if (accessToken && !config.headers.Authorization) {
            config.headers.Authorization = getAccessToken()
        }
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
        const res = response.data

        if (res.status == 401) {
            const {
                data
            } = res;
            // 缺乏/篡改AccessToken或RefreshToken 
            if (data == 'unauthorized' || data == 'tampered') {
                removeAccessToken()
                removeRefreshToken()
                Message({
                    message: res.msg,
                    type: "error",
                    duration: 5 * 1000
                })
                return router.push("/login");
            }
            // AccessToken 已过期或注销
            if (!isRefreshing) {
                isRefreshing = true
                if (data == 'access') {

                    removeAccessToken();
                    let refreshToken = getRefreshToken()
                    console.log(refreshToken)
                    if (!refreshToken) router.push("/login")
                        // 刷新RefreshToken
                    Refresh(refreshToken).then(success => {
                        // 刷新accessToken成功
                        if (success.status == 200) {
                            const newAccessToken = success.data.AccessToken
                                // 设置AccessToken
                            setAccessToken(newAccessToken)
                                // 重新发送请求队列中的请求
                                // requestsQueue.forEach(cb => cb(newAccessToken));
                                // requestsQueue = [];
                            window.location.reload();

                            // 或者使用路由跳转到当前页面
                            router.replace(router.currentRoute);
                            return service(response.config);
                        }
                        // refreshToken失效
                        else {
                            removeAccessToken();
                            removeRefreshToken();
                            Message({
                                message: "登录已过期",
                                type: "error",
                                duration: 5 * 1000
                            });
                            return router.push("/login");
                        }
                    }).finally(() => {
                        isRefreshing = false
                    })
                } else {
                    // 当前有请求正在刷新AccessToken，将当前请求加入队列中
                    return new Promise(resolve => {
                        requestsQueue.push(token => {
                            config.headers.Authorization = token;
                            resolve(service(config));
                        });
                    });
                }
            } else if (data == 'refresh') {
                return router.push("/login")
            }

        }
        if (res.status == 409) {
            Message({
                message: '请求过于频繁,请稍后再试',
                type: 'error',
                duration: 5 * 1000
            })
        }
        if (res.status == 403) {
            Message({
                message: res.msg,
                type: 'error',
                duration: 5 * 1000
            })
        }
        if (res.status === 500) {
            // to re-login
            return MessageBox.confirm('网络错误', {
                confirmButtonText: 'Re-Login',
                cancelButtonText: 'Cancel',
                type: 'warning'
            }).then(() => {})
        }
        if (res.status == 503) {
            Message({
                    message: res.msg,
                    type: 'error',
                    duration: 5 * 1000
                })
                // 跳回主页
            if (res.data == 'module') {
                router.push("/dashboard")

            } else if (res.data == 'licence') {
                store.dispatch('user/logout', payload)
            }
        }
        return res

    },
    error => {
        console.log('err' + error) // for debug
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service